<template>
  <div>
    <label>经度：</label>
    <input type="text" v-model="lng" />
    <br />
    <label>纬度：</label>
    <input type="text" v-model="lat" />
    <br />
    <button @click="getLocation">获取地址</button>
    <p>{{ address }}</p>
  </div>
</template>

<script>
import { ref } from "vue";
import AMapLoader from "@amap/amap-jsapi-loader";

export default {
  setup() {
    const lng = ref("");
    const lat = ref("");
    const address = ref("");

    const getLocation = () => {
      const longitude = parseFloat(lng.value);
      // console.log(longitude)
      const latitude = parseFloat(lat.value);
      // console.log(latitude)
      if (isNaN(longitude) || isNaN(latitude)) {
        alert("请输入有效的经纬度");
        return;
      }

      // 加载 AMap JS API
      AMapLoader.load({
        key: "f819c82141a53cedf6c86346c694e12f",
        version: "2.0",
      }).then((AMap) => {
        // 创建地理编码对象
        const geocoder = new AMap.Geocoder({
          city: "010", // 设置城市编码
        });

        // 根据经纬度获取地址信息
        geocoder.getAddress([longitude, latitude], (status, result) => {
          if (status === "complete" && result.info === "OK") {
            address.value = result.regeocode.formattedAddress;
          } else {
            alert("获取地址失败");
          }
        });
      });
    };

    return {
      lng,
      lat,
      address,
      getLocation,
    };
  },
};
</script>
